'''

    System Event Layer for Win32 platform

infos:
    http://kvance.livejournal.com/985732.html

'''

import time, threading
import pyHook
import win32com.client

_THREAD = None
_SHELL = None

def OnMouseEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Position:',event.Position
    print 'Wheel:',event.Wheel
    print 'Injected:',event.Injected
    print '---'
    
    # return True to pass the event to other handlers
    # return False to stop the event from propagating
    return True
    
def OnKeyboardEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended
    print 'Injected:', event.Injected
    print 'Alt', event.Alt
    print 'Transition', event.Transition
    print '---'
    
    # return True to pass the event to other handlers
    # return False to stop the event from propagating
    return True

def tap():
    # create the hook mananger
    hm = pyHook.HookManager()
    
    # register two callbacks
    hm.MouseAllButtonsDown = OnMouseEvent
    hm.KeyDown = OnKeyboardEvent
    
    # hook into the mouse and keyboard events
    hm.HookMouse()
    hm.HookKeyboard()
    
    # Start the pumping
    import pythoncom
    pythoncom.PumpMessages()

def x():
    nb = 5
    speed = 1
    for i in range(nb):
        time.sleep(speed)
        print "threaded print", nb-i
        
def hook():
    global _THREAD
    global _SHELL
    
    _SHELL=win32com.client.Dispatch("WScript.Shell")
#    thread.start_new_thread(tap,())
    _THREAD=threading.Thread(None, tap, "shikEventHook", (), {})
    _THREAD.start()
    print _THREAD._Thread__stop()
    
def stop():
    global _THREAD
    _THREAD._Thread__stop()
    
def emit(key):
    '''
    key must be like:
        "a"
        "+a"
        "^a"
        "%a"
        "^+a"
        "{DELETE}"
        "{TAB}"
        ...
    '''
    global _SHELL
    _SHELL.SendKeys(keys)


            
if __name__ == '__main__':
    hook()
    print "Pumping is on..."
    nb = 5
    speed = 2
    for i in range(nb):
        time.sleep(speed)
        print nb-i
        if nb > 3:
            stop()
    print "Pumping is off."

  